import store from '@/common/store'
import api from '@/common/request/index'
import base from "@/config/baseUrl";

// 获取链接参数
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}


/**
 * 获取url中的参数
 */
export const getUrlData = () => {
	var strs;
	var url = window.location.href; //获取url中"?"符后的字串
	var theRequest = new Object();
	if (url.indexOf("?") != -1) {
		url = url.substr(url.indexOf("?"));
		var str = url.substr(1);
		strs = str.split("&");
		for (var i = 0; i < strs.length; i++) {
			var index = strs[i].indexOf("=");
			theRequest[strs[i].slice(0, index)] = unescape(strs[i].slice(index + 1, strs[i].length));
		}
	}
    
	return theRequest;
}

// h5登录
export const h5Login = (callback) => {
	var get_Request = getUrlData();
	var getRequest = {
		code:'',
		member_token:''
	};
	if (get_Request.query){
		getRequest = JSON.parse(decodeURIComponent(get_Request.query));
	}
	console.log('getRequest',getRequest)
    if (isWechat()) {
		
		if (getRequest.member_token) {
			console.log('token-login')
				api('user.tokenLogin', {
					token:getRequest.member_token,
					bid:getRequest.bid
				}).then(res => {
					console.log('token-login',res)
						if (res.code==200){
								store.commit('USER_INFO',res.data);
								store.commit('TOKEN_INFO',res.data.member_token);
								uni.setStorageSync("fromLogin", ""); //要跳转到的页面
								store.dispatch('setTokenAndBack',res.data.member_token);
							let bussiness = {
								bid:res.data.bid,
							};
							store.commit("setbasebusinessID",bussiness);
							store.commit('setLoginPopupShow', false);
							uni.showToast({title: "登录成功"});
						}else{
							uni.showToast({title: "登录失败"});
						}
				}).catch((e)=>{
					 console.log(e);
				});
			return;
		}else if (getRequest.code) {
			
			let httpData = {
				wxSmallCode: getRequest.code, //小程序code
				bid:store.state.user.bid
			};
			console.log('code---',httpData)
			 api('user.officodeLogin', {
					httpData:httpData,
			 }).then(res => {
				 console.log('code---',res)
						if (res.code==200){
								store.commit('USER_INFO',res.data);
								store.commit('TOKEN_INFO',res.data.member_token);
								uni.setStorageSync("fromLogin", ""); //要跳转到的页面
								store.dispatch('setTokenAndBack',res.data.member_token);
							let bussiness = {
								bid:res.data.bid,
							};
							store.commit("setbasebusinessID",bussiness);
							store.commit('setLoginPopupShow', false);
							uni.showToast({title: "登录成功"});
						}else{
							uni.showToast({title: "登录失败"});
						}
			 }).catch((e)=>{
				console.log(e);
			 });
		}else{
				
				// 公众号登录
				var local = encodeURIComponent(window.location.href);
				var url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + base.publicAppId + "&redirect_uri=" + local + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
				var code = getUrlParam("code");
				if (!code) {
					window.location = url;
				} else {
						console.log('h5请求code---',code)
						  let httpData = {
							wxSmallCode: code, //小程序code
							bid:store.state.user.bid
						  };
						  
						api('user.officodeLogin', {
							httpData:httpData,
						   }).then(res => {
							   console.log('h5请求code---',res)
								if (res.code==200){
										store.commit('USER_INFO',res.data);
										store.commit('TOKEN_INFO',res.data.member_token);
										uni.setStorageSync("fromLogin", ""); //要跳转到的页面
										store.dispatch('setTokenAndBack',res.data.member_token);
									let bussiness = {
										bid:res.data.bid,
									};
									store.commit("setbasebusinessID",bussiness);
									store.commit('setLoginPopupShow', false);
									uni.showToast({title: "登录成功"});
								}else{
									uni.showToast({title: "登录失败"});
								}
						   }).catch((e)=>{
								console.log(e);
						   });

				}
			
			
			
		}
		
    } else {
        // 通用登录页--验证码登录
        uni.showModal({
        	title:"温馨提示",
        	content:"您还未登录，请先登录~",
        	confirmText: "去登录",
        	cancelText: "再逛会",
        	success: (res) => {
        		if(res.confirm){
        			uni.navigateTo({ url: '/pages/componentsC/account/login/pwd-login'})
        		}
        	}
        });
    }
}
// 浏览器判断是否微信
export const isWechat = () => {
	let ua = navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == "micromessenger") {
		//console.log('是微信客户端')  
		return true;  
	}else{
        //console.log('不是微信客户端')  
        return false;  
    }
};